// userLocal.js 用户本地存储操作工具，包含用户增删查改等方法
const USER_KEY = 'users';
const LOGIN_KEY = 'currentUser';

export function getUserList() {
  return JSON.parse(localStorage.getItem(USER_KEY) || '[]');
}

export function saveUserList(list) {
  localStorage.setItem(USER_KEY, JSON.stringify(list));
}

export function addUser(user) {
  const list = getUserList();
  user.id = Date.now();
  list.push(user);
  saveUserList(list);
}

export function updateUser(user) {
  const list = getUserList();
  const idx = list.findIndex(i => i.id === user.id);
  if (idx !== -1) {
    list[idx] = user;
    saveUserList(list);
  }
}

export function deleteUser(ids) {
  let list = getUserList();
  list = list.filter(i => !ids.includes(i.id));
  saveUserList(list);
}

export function getUserByUsername(username) {
  return getUserList().find(i => i.username === username);
}

export function setCurrentUser(user) {
  localStorage.setItem(LOGIN_KEY, JSON.stringify(user));
}

export function getCurrentUser() {
  return JSON.parse(localStorage.getItem(LOGIN_KEY) || 'null');
}

export function logout() {
  localStorage.removeItem(LOGIN_KEY);
} 